package com.demo.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        //1.创建serverSocket进行端口监听
        ServerSocket server = new ServerSocket(10086); // 监听本机的10086端口
        System.out.println("服务开启成功，端口为：10086");
        //2.接受客户端的连接
        Socket client = server.accept();//获取到客户端到服务器的连接
        System.out.println("有客户端连接上来了：" + client.getRemoteSocketAddress().toString());
        //3.获取到输入输出流
        InputStream is = client.getInputStream();
//        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        OutputStream out = client.getOutputStream();
        out.write("hello client\n".getBytes());
        out.flush();
        byte[] bytes = new byte[1024];
        int len = -1;
        String str = null;
        //4.对流进行读取或者写实现业务
        while (true) {
            len = is.read(bytes); // 网络流会等待另一端的数据
            if (len == -1) break; // 说明客户端没有再发数据了
            str = new String(bytes, 0, len).trim(); // 将读取到数据转成字符串
            if (str.equalsIgnoreCase("exit")) break;
            out.write(("i don't know what u want?(" + str + ")\n").getBytes());
            out.flush();
            System.out.println("客户端发送了:" + str);
        }
        //5.可选的close
        out.close();
        is.close();
        client.close();
    }
}
